<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common >
      <van-button ref="btn" :data-id="item.id" :style="styles" :class="getBtnClass" @click="onSelected($event)">
        {{ item.bgUrl && item.bgUrl.length > 0 ? "" : item.commonAttr.title }}</van-button>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { CONTROL_TYPES } from '@/common/const-wb'
import { EventBus } from '@/store/index'
import { EVENT_HOVER_TYPES } from '@/common/events'
import { isHasOwnProperty, getCompIdByParam } from '@/plugins/utils'
import { convertCss } from '@/store/utils'

export default {
  mixins: [utils],
  setup () {
    return {
      isSelected: false,
      isDisabled: false,
      isGrey: false,
      isGreyClass: false,
    };
  },
  components: {
    InjectTemplate,
  },
  created() {
    if(!this.isH5Edit){
      this.commonAttr.color =  this.item.styles.color;
      this.commonAttr.backgroundColor =  this.item.styles.backgroundColor;

      EventBus.$off("btnStatus", this.setBtnGrey);
      EventBus.$on("btnStatus", this.setBtnGrey);

      //timer compareInComps
      if(this.commonAttr.isDisabled || this.commonAttr.isGrey) {
        EventBus.$off("refreshNumberDayExists", this.onRefreshNumberDayExists);
        EventBus.$on("refreshNumberDayExists", this.onRefreshNumberDayExists);

        const compId = getCompIdByParam(this.item.commonAttr.relateAttrCompId) || this.item.id
        const compData = this.componentMap[compId]
        if(compData.events.number){
          EventBus.$off("refreshDynamicData", this.onRefreshByNumber);
          EventBus.$on("refreshDynamicData", this.onRefreshByNumber);
        }
        this.setBtnStatusCompareInComps();
        this.setBtnDisabledByTimer();
      }
      if(this.item.commonAttr.groupInjectClassName){
        this.injectDomInCompData();
      }

      if(this.item.selectedBGUrl && this.item.selectedBGUrl.length > 0) {
        let img = new Image();
        img.src = this.item.selectedBGUrl;
      }
    }
  },
  computed: {
    getBtnClass(){
      return { "grayscale": this.isGreyClass, "wb-btn": true };
    }
  },
  mounted(){
    // if(!this.isH5Edit){
    //   if(this.item.events[EVENT_HOVER_TYPES.compareInComps.type]){
    //     this.refreshStyles();
    //   }
    // }
    this.convertCustomCss()
  },
  methods: {
    setBtnStatusCompareInComps() {
      if(this.item.events[EVENT_HOVER_TYPES.compareInComps.type]) {
        const numberMinusControlData = this.getItemControls[CONTROL_TYPES.number]
        if(numberMinusControlData) {
          let numberControlData;
          const syn_com_id = getCompIdByParam(numberMinusControlData.data.syn_com_id);
          if(syn_com_id) {
            numberControlData = this.controls[syn_com_id][CONTROL_TYPES.number];
          }
          let isGrey = false;
          let isDisabled = false;
          if (numberMinusControlData && numberControlData && numberControlData.data.isUid) {
            if(numberMinusControlData.data.onceGrowValue < 0) {
              const num = parseInt(numberControlData.data.num);
              const onceGrowValue = parseInt(numberMinusControlData.data.onceGrowValue);
              if (num - Math.abs(onceGrowValue) < 0) {
                isGrey = true;
                isDisabled = true;
              }
            }
          }
          if(this.commonAttr.isDisabled && isDisabled){
            this.isDisabled = true
            this.setBtnGreyClass();
            this.refreshStyles();
          }
          if(this.commonAttr.isGrey && isGrey){
            this.isGrey = true
            this.setBtnGreyClass();
            this.refreshStyles();
          }
        }
      }
    },
    setBtnGrey(btnStatus){
      // {"compId":"","isGrey":false,"isSelected":false}
      //在其他交互中改变按钮的状态
      if(isHasOwnProperty(btnStatus, "compId")){
        if(this.item.id == btnStatus.compId){
          this.refreshBtnStatus(btnStatus);
        }
      }else{
        this.refreshBtnStatus(btnStatus);
      }
    },
    refreshBtnStatus(btnStatus){
      if(isHasOwnProperty(btnStatus, "isGrey")){
        if(this.commonAttr.isGrey){
          this.setBtnGreyClass();
          this.isGrey = btnStatus.isGrey;
          this.refreshStyles();
        }
      }else if(isHasOwnProperty(btnStatus, "isSelected")){
        this.commonAttr.isSelected_ = this.isSelected = btnStatus.isSelected;
        this.refreshStyles();
      }else if(isHasOwnProperty(btnStatus, "isDisabled")){
        this.isDisabled = btnStatus.isDisabled;
        if(this.isDisabled) this.setBtnGreyClass();
        this.refreshStyles();
      }
    },
    onSelected(e){
      if(this.isH5Edit) {
        return
      }
      if(this.isDisabled && e || this.commonAttr.groupInjectClassName){
        e.stopPropagation();
        return
      }

      if(this.commonAttr.isSelected) {
        if(this.item.commonAttr.isRadioInGroup){
          EventBus.$emit("refreshRadioBtnGroup");
        }
        this.commonAttr.isSelected_ = this.isSelected = !this.isSelected;
        if(this.commonAttr.relateEventCompId){
          const relateEventCompId = getCompIdByParam(this.commonAttr.relateEventCompId);
          const compData = this.componentMap[relateEventCompId]
          compData.commonAttr.isSelected_ = this.commonAttr.isSelected_
        }
        this.refreshStyles();
      }
    },
    onRefreshByNumber() {
      //计数为灰色
      if(this.commonAttr.isGrey || this.commonAttr.isDisabled) {
        const compId = getCompIdByParam(this.item.commonAttr.relateAttrCompId) || this.item.id
        const numberItemData = this.controls[compId] && this.controls[compId][CONTROL_TYPES.number]
        const numberControlData = numberItemData.data;
        if(numberControlData && numberControlData.dayNum > 0 && numberControlData.dayNum >= parseInt(numberControlData.day_limit)){
          if(this.commonAttr.isGrey) {
            this.isGrey = true;
          } else {
            this.isDisabled = true;
          }
          this.setBtnGreyClass();
          this.refreshStyles();
        }
      }
    },
    setBtnDisabledByTimer() {
      const relateAttrCompId = getCompIdByParam(this.commonAttr.relateAttrCompId);
      let controlData;
      if(relateAttrCompId){
        controlData = this.controls[relateAttrCompId];
      }else{
        controlData = this.getItemControls;
      }
      if(controlData){
        if(controlData[CONTROL_TYPES.timer]){
          let end = 0
          let start = 0
          let now = 0
          let timerControlData = controlData[CONTROL_TYPES.timer];
          if(timerControlData.data.time && timerControlData.data.time.length > 0){
            start = new Date(timerControlData.data.time).getTime()
            end = new Date(timerControlData.data.endTime).getTime()
            now = new Date().getTime()
          }
          let startTime = 0
          let endTime = 0
          startTime = now - start
          endTime = end - now
          let isDisabled_ = false;
          if(startTime < 0) {
            isDisabled_ = true
            // this.showToast("亲，活动还未开始！！请耐心等待！！");
          }else if(endTime < 0){
            isDisabled_ = true
            // this.showToast("亲， 活动已结束了哦！！");
          }else{
            isDisabled_ = false
          }
          this.isDisabled = isDisabled_
          if(this.isDisabled) this.setBtnGreyClass();
          this.refreshStyles();
        }
      }
    },
    setBtnGreyClass() {
      this.isGreyClass = false;
      if(!this.item.selectedBGUrl) {
        if(this.isDisabled) {
          this.isGreyClass = true;
        }
      }
    },
    onRefreshNumberDayExists({compId, isNumber}){
      if(this.item.id == compId){
        if(this.commonAttr.isGrey){
          this.setBtnGreyClass();
          this.isGrey = !isNumber;
        }else{
          this.isDisabled = !isNumber;
          if(this.isDisabled) this.setBtnGreyClass();
        }
        this.refreshStyles();
      }
    },
    refreshStyles(){
      let commonAttr = this.item.commonAttr
      // styles.backgroundColor = "transparent"
      let styles = {};

      if(this.isSelected || this.isDisabled || this.isGrey) {
        if(this.item.selectedBGUrl && this.item.selectedBGUrl.length > 0){
          styles.backgroundImage = "url(" + this.item.selectedBGUrl + ")"
        }else{
          styles.color = commonAttr.selectedColor
          styles.backgroundColor = commonAttr.selectedBGColor
        }
      }else{
        if(this.item.bgUrl && this.item.bgUrl.length > 0){
          styles.backgroundImage = "url(" + this.item.bgUrl + ")"
        }else{
          styles.color = commonAttr.color
          styles.backgroundColor = commonAttr.backgroundColor
        }
      }
      this.$store.commit("updateComponentAttr", {id: this.item.id, styles});
    },
    onRefreshCommonAttr() {
      this.convertCustomCss();
    },
    getCompDom() {
      return this.$refs.btn && this.$refs.btn.$el
    },
    convertCustomCss() {
      let customCssStr = this.commonAttr.customCssStr
      if(customCssStr) {
        let cssArr = convertCss(customCssStr).split(";");
        let keyValueArr;
        let dom = this.getCompDom();
        let textDom = dom.getElementsByClassName("van-button__text")[0];
        if(dom) {
          let bgStyle = dom.style;
          let textDomStyle = textDom.style;
          let key;
          _.forEach(cssArr, (keyValue) => {
            keyValueArr = keyValue.split(":");
            key = keyValueArr[0].replace(/[\r\n]/g,"");
            bgStyle[key] = keyValueArr[1];
            textDomStyle[key] = keyValueArr[1];
          })
        }
      }
    },
  },
  beforeUnmount(){
    if(this.isH5Edit) {
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
    }
    this.item.vueContainer = null;
    if(this.commonAttr.isDisabled || this.commonAttr.isGrey){
      EventBus.$off("refreshNumberDayExists", this.onRefreshNumberDayExists);
      if(this.numberItemData){
        EventBus.$off("refreshDynamicData", this.onRefreshByNumber)
      }
    }
    if(this.commonAttr.groupInjectClassName){
      EventBus.$off("btnStatus", this.setBtnGrey);
    }
    this.commonAttr.isSelected_ = this.isSelected = false;
  }
};
</script>

<style lang="scss">
.wb-btn {
  width: inherit;
  height: inherit;

  border: none;
  outline: none;

  // box-shadow: rgb(159 180 242) 0px 0px 17px -9px;
  // background: linear-gradient(rgb(120, 146, 194) 5%, rgb(71, 110, 158) 100%) rgb(120, 146, 194);
  // text-shadow: rgb(40 57 102) 0px 5px 18px;

}
.grayscale {
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
}

.rotation-animate {
  -webkit-animation: rotating 1.2s linear infinite;
  -moz-animation: rotating 1.2s linear infinite;
  -o-animation: rotating 1.2s linear infinite;
  animation: rotating 1.2s linear infinite
}

@-webkit-keyframes rotating {
  from { -webkit-transform: rotate(0) }
  to { -webkit-transform: rotate(360deg) }
}

@keyframes rotating {
  from { transform: rotate(0) }
  to { transform: rotate(360deg) }
}
@-moz-keyframes rotating {
  from { -moz-transform: rotate(0) }
  to { -moz-transform: rotate(360deg) }
}

</style>
